﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Notification;
using System.Collections.ObjectModel;

namespace G.Reader.Utils
{
    public static class PushHelp
    {
        private const string ChannelName = "G.Reader.Channel";
        public static HttpNotificationChannel PushChannel { get; private set; }
        public static void CreatePush()
        {
            PushChannel = HttpNotificationChannel.Find(ChannelName);
            Uri[] AllowedDomains =
                {
            //下面添加允许的地址，比如可能的后台图片地址，这里是客户端唯一需要注意的地方，只有在这里添加了可能的地址，服务端才能将图片信息推送到这里
            //new Uri( "http://pic.cnblogs.com/face/u27545.jpg")
                };
            try
            {
                if (PushChannel == null)
                {
                    PushChannel = new HttpNotificationChannel(ChannelName);
                    PushChannel.ChannelUriUpdated += pushChannel_ChannelUriUpdated;
                    PushChannel.Open();
                }
                else
                {
                    //PushService.PushServiceClient client = new PushService.PushServiceClient();
                    //client.AddPushInfoAsync(new PushService.PushInfo() { PushAddress = PushChannel.ChannelUri.OriginalString, UDID = UserDeviceInfo.GetDeviceUniqueId() });
                    //client.AddPushInfoCompleted += new EventHandler<PushService.AddPushInfoCompletedEventArgs>(client_AddPushInfoCompleted);
                    PushChannel.ChannelUriUpdated += pushChannel_ChannelUriUpdated;
                }
                PushChannel.ConnectionStatusChanged += pushChannel_ConnectionStatusChanged;
                PushChannel.ShellToastNotificationReceived += pushChannel_ShellToastNotificationReceived;
                PushChannel.HttpNotificationReceived += pushChannel_HttpNotificationReceived;
                PushChannel.BindToShellToast();
                PushChannel.BindToShellTile(new Collection<Uri>(AllowedDomains));
            }
            catch
            {
                //此处做异常处理，暂时未知会有何异常，待后面研究
            }

        }

        static void pushChannel_ConnectionStatusChanged(object sender, NotificationChannelConnectionEventArgs e)
        {
            //如果断开连接，那么重新连接
            if (e.ConnectionStatus == ChannelConnectionStatus.Disconnected)
            {
                try
                {
                    (sender as HttpNotificationChannel).Open();
                }
                catch { }
            }
        }

        static void pushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {

        }

        static void pushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
        {
            if (RecivedRaw != null)
            {
                //e.Notification.Body.CopyTo(
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    e.Notification.Body.CopyTo(stream);
                    RecivedRaw(null, new ReciveRawArgs() { Messasge = stream.GetBytes() });
                }
            }
        }

        static void pushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
            PushService.PushServiceClient client = new PushService.PushServiceClient();
            var pushinfo = new PushService.PushInfo() { PushAddress = e.ChannelUri.OriginalString, UDID = UserDeviceInfo.GetDeviceUniqueId() };
            if (GloabalData.Instance.User != null)
                pushinfo.UserId = GloabalData.Instance.User.Id;
            client.AddPushInfoAsync(pushinfo);
            client.AddPushInfoCompleted += new EventHandler<PushService.AddPushInfoCompletedEventArgs>(client_AddPushInfoCompleted);
        }

        static void client_AddPushInfoCompleted(object sender, PushService.AddPushInfoCompletedEventArgs e)
        {
            if (e.Result.IsOk)
            {
                GloabalData.Instance.PushInfo = e.pushinfo;
            }
        }
        public static event ReciveRawHandel RecivedRaw;

    }

    public delegate void ReciveRawHandel(object obj, ReciveRawArgs e);

    public class ReciveRawArgs : EventArgs
    {
        public byte[] Messasge { get; set; }
    }
}
